package com.itheima.filter;

import com.itheima.domain.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*
登录认证的过滤器
*/
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //1、对象转换
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpServletResponse resp= (HttpServletResponse) servletResponse;
        //放行的条件：session中去登陆者信息，如果有值，则表明登录过，如果为null表示还没有登录
        //不必要的资源放行：login.jsp
        String uri = req.getRequestURI();
        //截取出/login.jsp
        String path = uri.substring(uri.lastIndexOf("/"));
        System.out.println(path);
        if("/login.jsp".equals(path) || "/login".equals(path)||"/demo.css".equals(path)){
            filterChain.doFilter(req,resp);//放行
            return;
        }
        //2、获取session对象
        HttpSession session = req.getSession();
        //3、从session中获取user
        User user = (User) session.getAttribute("user");
        if(user!=null){
            //登录成功
            filterChain.doFilter(req,resp);//放行
            return;
        }
            //未登录
        resp.sendRedirect(req.getContextPath()+"/login.jsp");
    }
}
